<template>
  <div class="search">
    <Card >
      <Row type="flex" justify="space-between">
        <Col span="6">
          <div style="margin-top: 5px;padding-left:16px;">
            <Button @click="addDict" type="primary" icon="md-add">添加字典</Button>
            <Dropdown style="margin-left: 5px" @on-click="dropDownClick">
              <Button>更多操作<Icon type="ios-arrow-down"></Icon>
              </Button>
              <DropdownMenu slot="list">
                <DropdownItem name="editDict">编辑字典</DropdownItem>
                <DropdownItem name="deleteDict">删除字典</DropdownItem>
                <DropdownItem name="refresh">刷新</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
          <div style="padding-left:16px;height: 100%; margin-top: 5px">
            <Row>
              <Alert show-icon>
                当前选择：
                <div v-if="dictData.title!=null" style="display: inline">
                  <span class="select-count">{{dictData.title}}</span>
                  <a class="select-clear" @click="cancelSelect">取消选择</a>
                </div>
              </Alert>
            </Row>
            <Input
              suffix="ios-search"
              v-model="dictName"
              @on-change="searchDict"
              placeholder="输入字典名称"
              clearable
            />
            <div class="tree-bar" :style="{maxHeight: maxHeight}">
              <Tree ref="dictTree" :data="treeData" @on-select-change="selectDict"></Tree>
              <Spin size="large" fix v-if="treeLoading"></Spin>
            </div>
          </div>
        </Col>
        <Col span="17">
          <Row @keydown.enter.native="handleSearch">
            <Form ref="queryForm" :model="queryForm" inline :label-width="70">
              <Form-item label="字典值" prop="itemText">
                <Input
                  type="text"
                  v-model="queryForm.itemText"
                  clearable
                  placeholder="请输入字典值"
                  style="width: 200px"
                />
              </Form-item>
              <Form-item label="状态" prop="itemValue">
                <Select v-model="queryForm.status" style="width:200px">
                  <Option :value="1">启用</Option>
                  <Option :value="0">禁用</Option>
                </Select>
              </Form-item>
              <Form-item style="margin-left:-35px;" class="br">
                <Button @click="searchItemDict" type="primary" size="large" icon="ios-search">搜索</Button>
                <Button @click="handleReset" size="large">重置</Button>
              </Form-item>
            </Form>
          </Row>
          <Row class="operation">
            <Button @click="addDictValue" size="large" type="primary" icon="md-add">添加字典值</Button>
            <Button @click="deleteAll" size="large" icon="md-trash">删除</Button>
          </Row>
          <Row>
            <Alert show-icon>
              已选择
              <span class="select-count">{{selectCount}}</span> 项
              <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
          </Row>
          <Row>
            <Table
              :loading="loading"
              border
              :columns="columns"
              :data="data"
              sortable="custom"
              @on-sort-change="changeSort"
              @on-selection-change="showSelect"
              ref="table"
            ></Table>
          </Row>
          <Row type="flex" justify="end" class="page">
            <Page
              :current="queryForm.pageNum"
              :total="total"
              :page-size="queryForm.pageSize"
              @on-change="changePageNum"
              @on-page-size-change="changePageSize"
              :page-size-opts="[10,20,50]"
              size="small"
              show-total
              show-elevator
              show-sizer
            ></Page>
          </Row>
        </Col>
      </Row>
      <dict-form @ok="handlerSuccess" ref="dictFormModal"></dict-form>
      <dict-item-form @ok="itemSuccess" ref="dictItemForm"></dict-item-form>
    </Card>
  </div>
</template>

<script>
import {dictTree,deleteDict,findDictItemList,deleteDictItem} from "@/api/dict";
import DictForm  from "@/view/admin/form/DictForm";
import DictItemForm from "@/view/admin/form/DictItemForm";
import TreeSelect from "_c/tree-select/tree-select";
import {deleteUser} from "@/api/user";
export default {
  name: "Dict",
  components:{
    TreeSelect,
    DictForm,
    DictItemForm
  },
  data(){
    return{
      queryForm: {
        pageNum:1,
        pageSize:10,
        dictId:'',
        itemText:'',
        status:null,
      },
      dictName:'',
      loading:false,
      treeLoading:false,
      treeData:[],
      maxHeight: "500px",
      dictData:{},
      columns:[
        {
        type: "selection",
        width: 60,
        align: "center",
        fixed: "left"
      },
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          title: "字典项名称",
          key: "itemText",
          align: 'center',
          minWidth: 100,
          sortable: true,
        },
        {
          title: "字典名称",
          key: "itemValue",
          align: "center",
          minWidth: 100,
        },
        {
          title: "创建时间",
          key: "createTime",
          sortable: true,
          align: 'center',
          minWidth: 100,
        },
        {
          title: "操作",
          key: "action",
          align: 'center',
          width: 300,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.row);
                    }
                  }
                },
                " 编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        },
      ],
      rules:{
        dictCode:[
          {required:true,message:'请输入字典编码',trigger:'blur'},
        ],
        dictName:[
          {required:true,message:'请输入字典名称',trigger:'blur'},
        ],
        sort:[
          {type:'number',required:true,message:'请输入排序值',trigger:'blur'},
        ],
      },
      data:[],
      total:null,
      selectCount:null,
      modelType:1,
      selectList:[],
    }
  },
  methods: {
    handleSearch(){
      this.initDictTree();
    },
    handleReset(){
      this.$refs.queryForm.resetFields();
      this.initDictTree();
    },
    cancelSelect(){
     this.dictData={};
     let nodes = this.$refs.dictTree.getSelectedNodes();
     nodes.forEach( (node) => {
       node.selected=false;
     })
    },
    queryDictItem(){
      this.loading=true;
      findDictItemList(this.queryForm).then(res=>{
         if(res.code===200){
            this.data=res.data.records;
            this.total=res.data.total;
            this.loading=false
         }
      })
    },
    addDict(){
      this.$refs.dictFormModal.title='添加字典'
      this.$refs.dictFormModal.add();
    },
    searchItemDict(){
      this.queryDictItem();
    },
    changePage(v){
    },
    searchDict(){
      this.initDictTree();
    },
    addDictValue(){
      if(Object.keys(this.dictData).length===0){
        this.$Message.warning("请选择一个字典类别");
        return;
      }
      this.$refs.dictItemForm.title='添加字典值';
      this.$refs.dictItemForm.form.dictId=this.dictData.id;
      this.$refs.dictItemForm.add();
    },
    edit(obj){
      this.$refs.dictItemForm.title='修改字典值';
      this.$refs.dictItemForm.edit(obj);
    },
    dropDownClick(name){
      if(name==='editDict'){
         if(Object.keys(this.dictData).length===0){
           this.$Message.warning("请选择要编辑的字典");
           return;
         }
        this.$refs.dictFormModal.title='修改字典【'+this.dictData.title+"】"
        this.$refs.dictFormModal.edit(this.dictData);
      }
      if(name==='deleteDict'){
        if(Object.keys(this.dictData).length===0){
          this.$Message.warning("请选择要删除的字典");
          return;
        }
        this.removeDict();
      }
      if(name==='refresh'){
          this.initDictTree();
      }
    },
    selectDict(value){
      if(value.length>0){
        this.dictData=value[0];
        this.queryForm.dictId=value[0].id;
        this.queryDictItem();
      }
    },
    removeDict(){
      this.$Modal.confirm({
        title: '提示',
        content: '您确认要删除【'+this.dictData.title+'】及字典值吗？！删除后无法恢复',
        onOk: () => {
          deleteDict(this.dictData.id).then(res=>{
            if(res.code===200){
              this.$Message.success('删除成功');
              this.$Modal.remove()
            }
            this.initDictTree();
          })
        }
      });
    },
    handlerSuccess(){
      this.initDictTree();
    },
    itemSuccess(){
      this.queryDictItem();
    },
    submitForm(){
      this.$refs.dictForm.validate((valid)=>{
        if(valid){
          this.submitLoading=true;
          let obj;
          if(this.modelType===1){
            obj=saveDict(this.form);
          }else{
            obj=updateDict(this.form);
          }
          obj.then(res=>{
            if(res.code===200){
               this.$Message.success('操作成功');
                this.submitLoading=false;
                this.close();
                this.initDictTree();
            }
          }).catch((error)=>{
            this.submitLoading=false;
          })
        }
      })
    },
    initDictTree(){
      this.treeLoading = true;
      dictTree({dictName:this.dictName}).then(res=>{
        if(res.code===200){
           this.treeData=res.data;
           this.treeLoading=false;
        }
      })
    },
    remove(row){
      this.selectList.push(row);
      this.selectCount=1;
      this.deleteAll();
    },
    deleteAll(){
      if(this.selectList.length<=0){
         this.$Message.warning('至少选择一条数据');
         return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content:"您确认要删除所选的 " + this.selectCount + " 条数据?",
        loading: true,
        onOk: () => {
          let data=this.selectList;
          let ids='';
          data.forEach(e=>{
            ids+=e.id+','
          })
          ids=ids.substring(0,ids.length-1);
          deleteDictItem({ids:ids}).then(res=>{
            if(res.code===200){
              this.$Message.success('操作成功');
            }
            this.queryDictItem();
            this.selectList = [];
            this.selectCount = 0;
            this.$Modal.remove()
          })
        }
      });
    },
    clearSelectAll(){
      this.selectCount=0;
      this.selectList=[];
      this.$refs.table.selectAll(false);
    },
    changeSort(){

    },
    showSelect(v){
      this.selectList=v;
      this.selectCount=v.length;
    },
    changePageNum(value){
      this.queryForm.pageNum = value;
      this.queryDictItem();
    },
    changePageSize(value){
      this.queryForm.pageSize =value;
      this.queryDictItem();
    }
  },
  mounted(){
    this.initDictTree();
    this.queryDictItem();
  }
}
</script>

<style lang="less">
@import "../../styles/tree&table-common.less";
.ivu-tree ul {
  list-style: none;
  margin: 0;
  padding: 0;
  font-size: 14px!important;
}
</style>
